package com.yonyou.pmclouds.enterprise.process;

import com.yonyou.pmclouds.basecom.bp.processor.MultiProcessor;
import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseVO;
import com.yonyou.pmclouds.personnel.entity.PersonnelVO;
import com.yonyou.pmclouds.personnel.rmiitf.PersonnelMaintain;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author chulf
 * @Date 2020/4/15
 * @Description 添加企业后 添加人员后置
 **/
@Component
public class InsertPersonnelAfterProcess implements SingleProcessor<EnterpriseVO>, MultiProcessor<EnterpriseVO> {

    @Autowired
    private PersonnelMaintain personnelMaintain;
    @Override
    public void process(EnterpriseVO vo, EnterpriseVO orig) throws BusinessException {
        insertPersonnel(new EnterpriseVO[]{vo});
    }

    @Override
    public void process(EnterpriseVO[] vos, EnterpriseVO[] origs) throws BusinessException {
        insertPersonnel(vos);
    }

    private void insertPersonnel(EnterpriseVO[] vos) throws BusinessException {
        if(vos == null || vos.length <= 0){
            return;
        }

        List<PersonnelVO> insertPersonnelList = new ArrayList<>();
        for(EnterpriseVO enterpriseVO : vos){

            PersonnelVO[] personnelVOS = enterpriseVO.getPersonnelVOS();
            if (ArrayUtils.isEmpty(personnelVOS)) {
                continue;
            }

            for (PersonnelVO personnelVO : personnelVOS) {
                personnelVO.setPkEnterprise(enterpriseVO.getPkEnterprise());
                personnelVO.setPkTenant(RuntimeEnvironment.getTenantId());

                insertPersonnelList.add(personnelVO);
            }
        }

        if(insertPersonnelList.size() <= 0){
            return;
        }

        List<PersonnelVO> personnelVOS = personnelMaintain.savePersonnels(insertPersonnelList.toArray(new PersonnelVO[]{}));

        Map<String, List<PersonnelVO>> personnelVOMap = new HashMap<>();
        for(PersonnelVO personnelVO : personnelVOS){
            List<PersonnelVO> personnelVOList = personnelVOMap.computeIfAbsent(personnelVO.getPkEnterprise(), k -> new ArrayList<>());
            personnelVOList.add(personnelVO);
        }

        for(EnterpriseVO enterpriseVO : vos){
            List<PersonnelVO> personnelVOList = personnelVOMap.get(enterpriseVO.getPkEnterprise());
            if(personnelVOList == null || personnelVOList.size() <= 0){
                continue;
            }

            enterpriseVO.setPersonnelVOS(personnelVOList.toArray(new PersonnelVO[]{}));
        }
    }
}
